//
//  OpenSDK_SmsView.m
//  OpenSDK
//
//  Created by 涂俊 on 2018/7/19.
//  Copyright © 2018年 WYHT. All rights reserved.
//

#import "OpenSDK_SmsView.h"
#import "OpenSDK_LoginManager.h"
#import "OpenSDK_Toast.h"
#import "OpenSDK_LoginLoadingView.h"
#import "OpenSDK_DataKeys.h"
#import "OpenSDK_UIManager.h"
#import "OpenSDK_Proxy.h"

#import "OpenSDK_UIUtil.h"
#import "OPKTracking.h"
#import "OPKCoreConfiguration.h"

@interface OpenSDK_SmsView ()
{
    int smsTimeTotal;
    NSTimer *timer;
}
@end

@implementation OpenSDK_SmsView

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _bgView.backgroundColor = UIColor.whiteColor;
    _bgView.layer.cornerRadius = 10;
    _bgView.layer.masksToBounds = true;
    
    // 输入法上移
    self.keyboardExtraMargin = 30;
    
    // 提示文字
    self.msgView.text = [@"发送至" stringByAppendingString:[self securePhoneNumberWith:self.mobile]];
    
    // 验证码输入框
    self.smsInputView.delegate = self;
    self.smsInputView.numberLength = 6;
    self.smsInputView.textColor = [UIColor colorWithRed:67/255.0 green:156/255.0 blue:1 alpha:1];
    self.smsInputView.textFont = [UIFont boldSystemFontOfSize:26];
    self.smsInputView.lineColor = [UIColor lightGrayColor];
    self.smsInputView.completeCallback = ^(NSString *text) {
        [self completeSecurityCode:text];
    };
    
    // 发送短信按钮
    [self.smsSendBtn setTitle: @"获取验证码" forState: UIControlStateNormal];
    
    // 点击背景，收起输入法
    [self.bgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didHideKeyboard:)]];
    
    // 是否已发送验证码
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval totalTime = [[self timeUserDefaults] doubleForKey:[self totalTimeKey]];
    NSTimeInterval lastTime = [[self timeUserDefaults] doubleForKey:[self timeKey]];
    NSTimeInterval timeLeft = totalTime - (currentTime - lastTime);
    if (timeLeft <= 0) {
        [self didClickSmsBtn:self.smsSendBtn];
    } else {
        self.smsSendBtn.hidden = YES;
        [self.smsSendBtn setEnabled:NO];
        [self countDown:timeLeft];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [[OPKTracking shared] pageView:OPKPageLoginCaptcha];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSUserDefaults *)timeUserDefaults {
    return [[NSUserDefaults alloc] initWithSuiteName:@"OPSMSTime"];
}

- (NSString *)timeKey {
    return [NSString stringWithFormat:@"%@yc%@", self.mobile, OpenSDK_S_SMS_MOBILE_LOGIN];
}

- (NSString *)totalTimeKey {
    return [NSString stringWithFormat:@"%@yc%@total", self.mobile, OpenSDK_S_SMS_MOBILE_LOGIN];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark - btn callback

- (IBAction)didClickSmsBtn:(id)sender {
    // 按钮清空，转菊花
    self.smsSendBtn.hidden = YES;
    [self.smsSendBtn setEnabled:NO];
    [self.smsBtnIndicator startAnimating];
    id delegate = ^(BOOL result, long validTime, NSString *err) {
        [self.smsBtnIndicator stopAnimating];
        if (result) {
            // 存储当时时间
            NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
            [[self timeUserDefaults] setDouble:currentTime forKey:[self timeKey]];
            [[self timeUserDefaults] setDouble:validTime/1000.0 forKey:[self totalTimeKey]];
            
            [[[OpenSDK_iToast makeText:@"短信验证码已发送，请注意查收"] setDuration:2000] show];
            // 短信验证码发送成功，开始倒计时
            [self countDown:validTime / 1000.0];
//            self->smsTimeTotal = validTime / 1000.0;
//            self->timer = [NSTimer scheduledTimerWithTimeInterval:1.0
//                                                     target:[OpenSDK_Proxy proxyWithTarget:self]
//                                                   selector:@selector(changeTimeWords)
//                                                   userInfo:nil
//                                                    repeats:YES];
//            self.countDownView.hidden = NO;
//            self.countDownView.text = [NSString stringWithFormat:@"%ds可重发", self->smsTimeTotal];
//            // 输入框获取焦点
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self.smsInputView becomeFirstResponder];
//            });
        } else {
            [[[OpenSDK_iToast makeText:err] setDuration:2000] show];
            self->smsTimeTotal=0;
            self.smsSendBtn.hidden = NO;
            [self.smsSendBtn setEnabled:YES];
            [self.smsSendBtn setTitle: @"重新发送" forState: UIControlStateNormal];
            // 返回上一级节目
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:NO];
            });
        }
    };
    if (self.isBind) {
//        [[OpenSDK_LoginManager getInstance] sendSMS:self.mobile smsType:OpenSDK_S_SMS_MOBILE_REGISTER
//                                           delegate:delegate];
        [[OpenSDK_LoginManager getInstance] sendSMS:self.mobile smsType:OpenSDK_S_SMS_MOBILE_BIND
                                           delegate:delegate];
    } else {
        [[OpenSDK_LoginManager getInstance] sendSMS:self.mobile smsType:OpenSDK_S_SMS_MOBILE_LOGIN
                                           delegate:delegate];
    }
}

// 倒计时
- (void)countDown:(int)count {
    // 短信验证码发送成功，开始倒计时
    self->smsTimeTotal = count;
    self->timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                             target:[OpenSDK_Proxy proxyWithTarget:self]
                                           selector:@selector(changeTimeWords)
                                           userInfo:nil
                                            repeats:YES];
    self.countDownView.hidden = NO;
    self.countDownView.text = [NSString stringWithFormat:@"%ds可重发", self->smsTimeTotal];
    // 输入框获取焦点
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.smsInputView becomeFirstResponder];
    });
}

// 定时器回调函数，每秒回调
- (void) changeTimeWords {
    if(smsTimeTotal > 0) {
        smsTimeTotal--;
        self.countDownView.hidden = NO;
        self.countDownView.text = [NSString stringWithFormat:@"%ds可重发", smsTimeTotal];
    } else {
        // 计时结束
        if (timer != nil) {
            [timer invalidate];
        }
        smsTimeTotal = 0;
        self.countDownView.hidden = YES;
        self.smsSendBtn.hidden = NO;
        [self.smsSendBtn setEnabled:YES];
        [self.smsSendBtn setTitle: @"重新发送" forState: UIControlStateNormal];
    }
}

- (IBAction)didClickBackBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:NO];
}

- (IBAction)didClickContactBtn:(id)sender {
    // 收起输入法
    [self didHideKeyboard:sender];
    //跳转到协议界面
    [[OpenSDK_UIManager getInstance] showNextUIWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_ContactView"];
}


#pragma mark - 完成验证码输入的回调

- (void)completeSecurityCode:(NSString *)securityCode {
    if (securityCode == nil || securityCode.length == 0) {
        [[[OpenSDK_iToast makeText:@"抱歉，请输入验证码"] setDuration:2000] show];
        return;
    }
    //清空验证码输入框
    [self.smsInputView clearText];
    
    // 先弹出loading框
    UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
    OpenSDK_LoginLoadingView *vc = (OpenSDK_LoginLoadingView *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_LoginLoadingView"];
    vc.accoutnName = [self securePhoneNumberWith:self.mobile];
    vc.order = self.order;
    [self.navigationController pushViewController:vc animated:NO];
    
    //调用接口请求服务器
    if (self.isBind) {
        vc.isHideSwitchAccount = YES;
        // 调用绑定接口
        [[OpenSDK_LoginManager getInstance] bindWithPhone:self.mobile securityCode:securityCode delegate:^(BOOL result, OpenSDK_AccountRecord *account, NSString *err) {
            if (!result) {
                // 绑定失败
                [[[OpenSDK_iToast makeText:err] setDuration:2000] show];
            }
            [vc loginResultCallback:result account:account];
        }];
    } else {
        vc.isHideSwitchAccount = NO;
        // 调用登录接口
        [[OpenSDK_LoginManager getInstance] loginWithPhone:self.mobile securityCode:securityCode delegate:^(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err) {
            if (!result) {
                // 登录失败
                [[[OpenSDK_iToast makeText:err] setDuration:2000] show];
            }
            [vc loginResultCallback:result account:account];
        }];
        // 统计
        [[OPKTracking shared] event:OPKEventLoginMobileEnd];
    }
}

- (NSString *)securePhoneNumberWith:(NSString *)number {
    if (number == nil) {
        return @"";
    }
    if (number.length <= 6) {
        return number;
    }
    NSInteger index = floor((number.length - 4) / 2.0);
    NSString *result = [number stringByReplacingCharactersInRange:NSMakeRange(index, 4) withString:@"****"];
    return result;
}

@end
